<template>
<div class="bfc my-student-page">
  <div class="student-list-table">
    <t-table
        row-key="index"
        :data="stuList"
        :columns="col"
    >
      <template #operation="slotProps">
        <t-button theme="danger" @click="handleDeleteStu(slotProps)"> 退选 </t-button>
      </template>
    </t-table>
  </div>
  <t-dialog
      v-model:visible="visible"
      theme="warning"
      header="警示"
      body="确定要移除该学生吗？"
      @confirm="onClickConfirm"
  />
</div>
</template>

<script setup lang="ts">
import {MessagePlugin} from 'tdesign-vue-next';
import { getStudentList, deleteStudent } from "../../api";
import {ref} from "vue";

const col = [
  {
    width: 100,
    colKey: 'name',
    title: '姓名',
  },
  {
    width: 150,
    colKey: 'account',
    title: '学号'
  },
  {
    width: 200,
    colKey: "class",
    title: "班级"
  },
  {
    colKey: 'operation',
    title: '操作',
    width: 100,
    cell: 'operation',
  },
]

const stuList = ref([]);
let currentIndex = ref(0);
let currentId = ref("");
let visible = ref(false);

getStudentList(JSON.stringify(JSON.parse(<string>sessionStorage.getItem("userInfo")).studentList)).then(res=>{
  stuList.value = res.data.studentList;
})

function handleDeleteStu(e: any){
  currentIndex.value = e.rowIndex;
  currentId.value = e.row._id;
  visible.value = true;
}

function onClickConfirm(){
  deleteStudent(JSON.parse(<string>sessionStorage.getItem("userInfo"))._id,currentId.value).then(res=>{
    stuList.value.splice(currentIndex.value, 1);
    //更新本地缓存
    let u = JSON.parse(<string>sessionStorage.getItem("userInfo"));
    u.studentList = stuList.value;
    sessionStorage.setItem("userInfo", JSON.stringify(u));
    visible.value = false;
    MessagePlugin.success(res.data.msg);
  })
}
</script>

<style scoped>
.student-list-table{
  width: 800px;
  padding: 50px;
  margin: 20px auto;
  box-shadow: 0 0 5px #ccc;
}
</style>
